import logging

import pymysql

# 配置日志
logger = logging.getLogger(__name__)


class DB:
    """
    数据库操作类
    """

    def __init__(self):
        try:
            self.conn = pymysql.connect(
                host="rm-2zer2f33rws29ogb1do.mysql.rds.aliyuncs.com",
                port=3306,
                user="zxy",
                password="zxy@800901",
                database="ruoyi",
                cursorclass=pymysql.cursors.DictCursor,
                charset='utf8mb4',
                use_unicode=True
            )
            logger.info("数据库连接成功")
        except Exception as e:
            logger.error(f"数据库连接失败: {str(e)}", exc_info=True)
            raise

    def query(self, sql, params=None):
        """
        执行查询SQL语句
        
        参数:
        sql (str): SQL查询语句
        params (tuple): 查询参数
        
        返回:
        list: 查询结果列表
        """
        try:
            with self.conn.cursor() as cursor:
                cursor.execute(sql, params)
                result = cursor.fetchall()
                return result
        except Exception as e:
            logger.error(f"执行查询失败: {str(e)}, SQL: {sql}, 参数: {params}", exc_info=True)
            raise

    def execute(self, sql, params=None):
        """
        执行更新SQL语句
        
        参数:
        sql (str): SQL更新语句
        params (tuple): 更新参数
        
        返回:
        int: 影响的行数
        """
        try:
            with self.conn.cursor() as cursor:
                rows = cursor.execute(sql, params)
                self.conn.commit()
                return rows
        except Exception as e:
            self.conn.rollback()
            logger.error(f"执行更新失败: {str(e)}, SQL: {sql}, 参数: {params}", exc_info=True)
            raise

    def __del__(self):
        """
        关闭数据库连接
        """
        try:
            if hasattr(self, 'conn') and self.conn:
                self.conn.close()
                logger.info("数据库连接已关闭")
        except Exception as e:
            logger.error(f"关闭数据库连接失败: {str(e)}", exc_info=True)
